import type { GlobalThemeOverrides } from 'naive-ui'
import { cloneDeep } from 'lodash-es'
import { themeSetting } from '@/settings'
import { useThemeStore } from '@/store'
import { addColorAlpha, getColorPalette, localStg } from '@/utils'
import { setTableCurrentColor } from '@/utils/common/table'
import { JBoltApi } from '@/utils/request'
import { ResData } from '@/typings/request'

/** 初始化主题配置 */
export function initThemeSettings() {
    let themeColor = ''
    try {
        // 生产环境才缓存主题配置，本地开发实时调整配置更改配置的json
        const storageSettings = localStg.get('themeSettings')
        if (storageSettings && Object.keys(storageSettings).length) {
            console.debug('从本地缓存加载主题设置', storageSettings)
            themeColor = storageSettings.themeColor
            return storageSettings
        }

        themeColor = localStg.get('themeColor') || themeSetting.themeColor
        const info = themeSetting.isCustomizeInfoColor
            ? themeSetting.otherColor.info
            : getColorPalette(themeColor, 7)
        const otherColor = { ...themeSetting.otherColor, info }
        const setting = cloneDeep({ ...themeSetting, themeColor, otherColor })
        return setting
    } finally {
        //加载主题的时候，将主题颜色设置为table的激活颜色
        setTableCurrentColor(themeColor)
    }
}

/**
 * 从服务端加载用户的主题设置
 */
export function loadThemeSettingFromServer() {
    JBoltApi.get<ResData>('/api/admin/userConfig?key=JBOLT_ADMIN_STYLE').then(
        ({ error, result }) => {
            if (error) {
                return
            }
            if (result?.data.configValue && result.data.configValue != 'default') {
                try {
                    const config = JSON.parse(result.data.configValue)
                    useThemeStore().$patch({ ...config, hasLoad: true })
                    setTableCurrentColor(config.themeColor)
                } catch (err) {
                    return
                }
            }
        }
    )
}

type ColorType = 'primary' | 'info' | 'success' | 'warning' | 'error'
type ColorScene = '' | 'Suppl' | 'Hover' | 'Pressed' | 'Active'
type ColorKey = `${ColorType}Color${ColorScene}`
type ThemeColor = Partial<Record<ColorKey, string>>

interface ColorAction {
    scene: ColorScene
    handler: (color: string) => string
}

/** 获取主题颜色的各种场景对应的颜色 */
function getThemeColors(colors: [ColorType, string][]) {
    const colorActions: ColorAction[] = [
        { scene: '', handler: (color) => color },
        { scene: 'Suppl', handler: (color) => color },
        { scene: 'Hover', handler: (color) => getColorPalette(color, 5) },
        { scene: 'Pressed', handler: (color) => getColorPalette(color, 7) },
        { scene: 'Active', handler: (color) => addColorAlpha(color, 0.1) }
    ]

    const themeColor: ThemeColor = {}

    colors.forEach((color) => {
        colorActions.forEach((action) => {
            const [colorType, colorValue] = color
            const colorKey: ColorKey = `${colorType}Color${action.scene}`
            themeColor[colorKey] = action.handler(colorValue)
        })
    })

    return themeColor
}

/** 获取naive的主题颜色 */
export function getNaiveThemeOverrides(
    colors: Record<ColorType, string>
): GlobalThemeOverrides {
    const { primary, success, warning, error } = colors

    const info = themeSetting.isCustomizeInfoColor
        ? colors.info
        : getColorPalette(primary, 7)

    const themeColors = getThemeColors([
        ['primary', primary],
        ['info', info],
        ['success', success],
        ['warning', warning],
        ['error', error]
    ])

    const colorLoading = primary

    return {
        common: {
            ...themeColors
        },
        LoadingBar: {
            colorLoading
        }
    }
}
